package com.samtech.web.controller;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.AbstractView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

@Controller
public class QrCodeController {
	//二维码颜色
    private static final int BLACK = 0xFF000000;

    //二维码颜色
    private static final int WHITE = 0xFFFFFFFF;
    @CrossOrigin(origins="*",maxAge=600)
	@RequestMapping(value="/qrcode",method= {RequestMethod.GET,RequestMethod.POST})
	public Object genImage(@RequestParam(name="url") final String url){
		AbstractView view=new AbstractView() {

			@Override
			protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
					HttpServletResponse response) throws Exception {
				Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();
		        //设置编码字符集
		        his.put(EncodeHintType.CHARACTER_SET, "utf-8");
		        his.put(EncodeHintType.ERROR_CORRECTION, "M");
		        his.put(EncodeHintType.MARGIN, "2");
				String text=model.get("url").toString();
				//1、生成二维码
	            final QRCodeWriter qrCodeWriter = new QRCodeWriter();
	            
				BitMatrix encode = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 100, 100, his);
				
	            //2、获取二维码宽高
	            int codeWidth = encode.getWidth();
	            int codeHeight = encode.getHeight();
	            System.out.println("with:"+codeWidth+";height:"+codeHeight);
	            //3、将二维码放入缓冲流
	            BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
	            //Graphics2D createGraphics = image.createGraphics();
	            //Raster data = image.getData();
	            //WritableRaster wraster = data.createCompatibleWritableRaster();
	            for (int i = 0; i < codeWidth; i++) {
	            	StringBuffer buf = new StringBuffer();
	                for (int j = 0; j < codeHeight; j++) {
	                    //4、循环将二维码内容定入图片
	                    final boolean b = encode.get(i, j);
	                    Color color=b?Color.BLACK:Color.WHITE;
						image.setRGB(i, j, color.getRGB());
						//buf.append(b?"*":" ");
	                    //wraster.setPixel(i, j, b?[BLACK]);
	                }
	               // System.out.println(buf.toString());
	            }
	          
	            //image.flush();
	            ServletOutputStream outputStream = response.getOutputStream();
	            ByteArrayOutputStream bstream = new ByteArrayOutputStream();
	            ImageIO.write(image, "png", bstream);
	            byte[] byteArray = bstream.toByteArray();
	            System.out.println("len:"+byteArray.length);
	            response.setContentLength(byteArray.length);
	            outputStream.write(byteArray, 0, byteArray.length);
	            outputStream.flush();
	            /*try {
	            outputStream.close();
	            }catch(IOException ex) {
	            	
	            }*/
			}
			
		};
		view.setContentType("image/png");
		
		ModelAndView modelAndView = new ModelAndView(view);
		modelAndView.getModel().put("url", url);
		return modelAndView;
	}
}
